package hsintiao.com.xintiaoAPP.controller;

import ch.qos.logback.core.util.FileUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import hsintiao.com.xintiaoAPP.annotation.PassToken;
import hsintiao.com.xintiaoAPP.entity.HeartData;
import hsintiao.com.xintiaoAPP.entity.heart.CanShu;
import hsintiao.com.xintiaoAPP.entity.single.SingleArray;
import hsintiao.com.xintiaoAPP.entity.single.SingleLong;
import hsintiao.com.xintiaoAPP.entity.single.SingleLongArray;
import hsintiao.com.xintiaoAPP.heartfilter.*;
import hsintiao.com.xintiaoAPP.service.HeartDataService;
import hsintiao.com.xintiaoAPP.util.AjaxResult;
import hsintiao.com.xintiaoAPP.util.MultipartFileToFile;
import hsintiao.com.xintiaoAPP.util.ResponseCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.net.Socket;
import java.util.*;

@RestController
@RequestMapping("/heartData")
@CrossOrigin
public class HeartDataController {

    @Autowired
    private HeartDataService heartDataService;

     //分段获取心电数据，根据用户对应参数进行计算
    @PostMapping("/getHeartData")
    @ResponseBody
    @PassToken
    public AjaxResult getFilterData(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
                                      @RequestBody JSONObject jsonObject) {

        /*System.out.println("--------11111--------");
        httpServletResponse.setHeader("Content-type", "application/json;charset=UTF-8");
        httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
        httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS");
        httpServletResponse.setHeader("Access-Control-Max-Age", "86400");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", "*");

        // 如果是OPTIONS则结束请求
        if (HttpMethod.OPTIONS.toString().equals(httpServletRequest.getMethod())) {
            httpServletResponse.setStatus(HttpStatus.NO_CONTENT.value());
            return null;
        }*/
        try {
            JSONArray jsonArray = jsonObject.getJSONArray("arrayList");
            //获取userID
            String id = jsonObject.get("userID").toString();
            Long userID = Long.parseLong(id);
            System.out.println(userID);
            //获取字符串数组
            ArrayList<String> arrayList=(ArrayList<String>) JSONArray.toJavaObject(jsonArray,ArrayList.class);
            System.out.println("原始数据="+arrayList);
            //System.out.println(arrayList);
            //转换为数组类型，方便从下标截取数据
            Object[] strs = arrayList.toArray();
            System.out.println("原始长度="+strs.length);
            //获取数组长度，在数据库做标识
            Integer size1 = arrayList.size();
            Long size = Long.parseLong(size1.toString());

            AjaxResult result = heartDataService.getFilterData(size,userID,arrayList,strs);
            return result;
            /*Integer start = heartDataService.getStartNum(userID);
            ArrayList<Object> list = new ArrayList<>();
            if(start>0 && size>0){
                for(int i=start;i<strs.length;i++){
                    list.add(strs[i]);
                }
            }
            System.out.println(list);*/
            /*file1.delete();
            Long id = Long.parseLong(userID);
            System.out.println(userID);
            ArrayList<String> arrayList = this.getDataforFile(file);
            从数据库获取参数以及数据长度标识下标*/
            /*CanShu canShu = heartDataService.getCanShuforid(userID);
            if(canShu != null && canShu.getT_h()>0 && canShu.getSize()>0 ){

                //Integer start = heartDataService.getStartNum(size,userID);
                //获取上一次的参数(t_h，数据长度下标标识)
                int start = canShu.getSize();
                System.out.println("size="+start);
                arrayList = new ArrayList<>();
                if(start>0 && size>0){
                    for(int i=start;i<strs.length;i++){
                        arrayList.add(strs[i].toString());
                    }
                }
                System.out.println("数据="+arrayList.size());
                System.out.println(arrayList);
                MainFilter mainFilter = new MainFilter();
                mainFilter.setT_h(canShu.getT_h());
                mainFilter.setX(canShu.getX());
                mainFilter.setY(canShu.getY());
                mainFilter.domain(arrayList);
                //获取滤波数据，心率周期等
                List<Integer> rrs = mainFilter.getRrs();//心率周期
                List<Integer> rates = mainFilter.getRates();//心率
                Integer rr=0;
                Integer rate=0;
                for (Integer r:rrs) {
                    rr+=r;
                }
                for (Integer r:rates) {
                    rate+=r;
                }
                //计算
                if(rrs != null && rates != null && rr!=0 && rate !=0){
                    rr=(int)rr/rrs.size();
                    rate=(int)rate/rates.size();
                }else {
                    rr=10;
                    rate=10;
                }
                EventFlag mevent = mainFilter.getMevent();//异常
                HashMap<Object, Object> map = new HashMap<>();
                map.put("rrs",rr);
                map.put("rr",rr);
                map.put("rates",rate);
                map.put("rate",rate);
                System.out.println("rate="+rate);
                map.put("eventFlag",mevent);

                System.out.println("数据总行："+map.size());

                *//*fr.close();
                br.close();
                bop.close();
                op.close();*/
            /*

                //return AjaxResult.me().setResultObj(listmap);
                return AjaxResult.me().setMessage("没有错误").setResultObj(map);

            }else {
                //新的一次检测心电
                //将第一次的数据添加到字符串集合中
                arrayList = new ArrayList<>();
                for(int i=0;i<strs.length;i++){
                    arrayList.add(strs[i].toString());
                }
                //执行参数设置算法
                CanShuFilter canShuFilter = new CanShuFilter();
                canShuFilter.domain(arrayList);
                float t_h = canShuFilter.getT_h();
                float[] x = canShuFilter.getX();
                float[] y = canShuFilter.getY();
                heartDataService.saveCanShu(t_h,x,y,userID,size);
                //返回滤波数据，心率周期等
                return null;
            }*/
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("出现错误");
            return AjaxResult.me().setSuccess(false).setCode(201).setMessage("发生错误"+e.getMessage());
        }

    }


    //初始化参数-心电监测完毕后初始化参数
    @PostMapping("/inifData")
    @ResponseBody
    @PassToken
    public AjaxResult InifData(@RequestBody JSONObject jsonObject){
        try {
            String id = jsonObject.get("userID").toString();
            Long userID = Long.parseLong(id);
            //Long id = singleLong.getId();
            JSONArray jsonArray = jsonObject.getJSONArray("arrayList");
            ArrayList<String> arrayList=(ArrayList<String>) JSONArray.toJavaObject(jsonArray,ArrayList.class);
            /*ArrayList<String> list = new ArrayList<>();
            for (BigDecimal s :arrayList) {
                list.add(s.toString().trim());
            }*/
            //System.out.println(arrayList);
            heartDataService.InifDataCanShu(userID);
            AjaxResult result = heartDataService.saveHeartData(arrayList,userID);
            return result;
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setCode(201).setMessage("出现异常，请重试");
        }
    }

    //获取专业报告
    @PostMapping("/getProfessionalReport")
    @ResponseBody
    @PassToken
    public AjaxResult getProfessionalReport(@RequestBody JSONObject jsonObject){
        try {
            String id = jsonObject.get("userID").toString();
            Long userID = Long.parseLong(id);
            //Long id = singleLong.getId();
            JSONArray jsonArray = jsonObject.getJSONArray("arrayList");
            ArrayList<String> arrayList=(ArrayList<String>) JSONArray.toJavaObject(jsonArray,ArrayList.class);
            /*ArrayList<String> list = new ArrayList<>();
            for (BigDecimal bg:arrayList) {
                list.add(bg.toString().trim());
            }*/
            AjaxResult result = heartDataService.getProfessionalReport(arrayList,userID);
            return result;
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setCode(201).setMessage("出现异常，请重试");
        }

    }

    //调试用
    @PostMapping("/fileToArray")
    @ResponseBody
    @PassToken
    public AjaxResult fileToArray(@RequestParam("file") MultipartFile file){
        try {
            ArrayList<String> arrayList = this.getDataforFile(file);
            return AjaxResult.me().setResultObj(arrayList);
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setCode(201).setMessage("出错"+e.getMessage());
        }
    }
    //调试用
    @PostMapping("/toString")
    @ResponseBody
    public ArrayList<String> toStr(@RequestBody JSONObject jsonObject){
        try {
            String id = jsonObject.get("userID").toString();
            Long userID = Long.parseLong(id);
            //Long id = singleLong.getId();
            JSONArray jsonArray = jsonObject.getJSONArray("arrayList");
            ArrayList<BigDecimal> arrayList=JSONArray.toJavaObject(jsonArray,ArrayList.class);
            System.out.println(arrayList);
            ArrayList<String> list = new ArrayList<>();
            for (BigDecimal sf:arrayList
                 ) {
                String s = sf.toString();
                list.add(s);
            }
            System.out.println(list);
            return list;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }

    }
    //调试用
    @PostMapping("/getFilterData")
    @ResponseBody
    @PassToken
    public AjaxResult getFilterData(MultipartFile file,String userID){
        try {
            ArrayList<String> arrayList = this.getDataforFile(file);
            System.out.println(arrayList);
            HeartFilter filter = new HeartFilter();
            //原始数据
            //ArrayList<String> arrayList = this.getDataforFile(file);
            float[] floats = this.changeType(arrayList);
            //原始数据传递到算法中
            filter.domain(arrayList);
            //滤波后的数据
            float[] m_mydata = filter.getM_mydata();
            //保存心电数据

            List<Result> results = filter.getResults();
            System.out.println(results);
            EventFlag eventFlag = filter.getMevent();
            System.out.println(eventFlag);
            System.out.println(eventFlag);
            HashMap<Object, Object> map = new HashMap<>();
            map.put("results",results);
            map.put("eventFlag",eventFlag);
            map.put("data",arrayList);
            map.put("rrs",filter.getRrs());
            map.put("rates",filter.getRates());
            return AjaxResult.me().setResultObj(map);
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setCode(201).setMessage("出错"+e.getMessage());
        }
    }

    //float数组转换为字符串集合
    private ArrayList<String> changeTypeFloat(float[] data){
        ArrayList<String> arrayList = new ArrayList();
        for(int i=0;i<data.length;i++){
            arrayList.add(Float.toString(data[i]));
        }
        return arrayList;
    }
    //字符串聚合数组转换为float数组
    private float[] changeType(ArrayList<String> data){
        System.out.println("字符串数组长度="+data.size());
        float[] array =new float[data.size()];
        StringBuilder sb = new StringBuilder();
        for(int i=0;i<data.size();i++){
            array[i] =Float.parseFloat(data.get(i));
            sb.append(array[i]+",");
        }
        //System.out.println("数组="+sb);
        return array;
    }
    //从文件中获取数据转换为字符串集合数组
    private ArrayList<String> getDataforFile(MultipartFile file){
        FileReader fr = null;
        File f =null;
        try {
            //判断是否为空的文件
            if(file.equals("")||file.getSize()<=0){
                file = null;
            }else{
                //将复杂表单转换为file对象
                f = MultipartFileToFile.multipartFileToFile(file);
                /*FileOutputStream op = new FileOutputStream();
                byte[] bytes = file.getBytes();
                InputStream ins = file.getInputStream();
                f=new File(file.getOriginalFilename());
                FileUtil.inputStreamToFile(ins, f);*/
                //ins.close();
            }
            ArrayList<String> arrayList = new ArrayList();
            StringBuffer sb = new StringBuffer();
            fr = new FileReader(f);
            BufferedReader br = new BufferedReader(fr);
            String str;
            // 按行读取字符串
            while ((str = br.readLine()) != null) {
                //arrayList.add(str.substring(0,str.length()-1));
                arrayList.add(str.trim());
                sb.append(str.trim()+",");//读取文件中的数据，拼接字符串
            }
            fr.close();
            br.close();
            File file1 = new File(f.toURI());
            file1.delete();
            MultipartFileToFile.delteTempFile(f);
            return arrayList;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }finally {
            if(f.toURI()!= null){
                File file1 = new File(f.toURI());
                file1.delete();
            }
        }
    }

    @PostMapping("/getHeartDataForO")
    @ResponseBody
    @PassToken
    //查询其他人的心电(随机获取)
    public AjaxResult getHeartDataForO(){
        try {
            AjaxResult result = heartDataService.getRanData();
            return result;
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setCode(201).setMessage("出现错误");
        }
    }

    @PostMapping("/getHeartDataForLlist")
    @ResponseBody
    @PassToken
    //查询L的心电数据列表
    public AjaxResult getHeartDataForLlist(){
        try {
            AjaxResult result = heartDataService.getHeartDataForLlist();
            return result;
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setCode(201).setMessage("查询失败，请重试");
        }

    }

    @PostMapping("/getHeartDataForLID")
    @ResponseBody
    @PassToken
    //根据L列表中的id获取对应的心电数据
    public AjaxResult getHeartDataForLID(@RequestBody SingleLong singleLong){
        try {
            int a=1;
            Long dataID = singleLong.getId();
            if(dataID ==0 || dataID == null){
                a=0;
            }
            AjaxResult result = heartDataService.getHeartDataForLID(dataID,a);
            return result;
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setCode(201).setMessage("查询失败，请重试");
        }
    }

    @PostMapping("/saveRandata")
    public void saveRandata(){
        try {
            FileReader fr = new FileReader("E:\\work\\data2\\zhao1-1滤波前.txt");
            BufferedReader bf = new BufferedReader(fr);
            String str;
            ArrayList<String> arrayList = new ArrayList<>();
            while ((str = bf.readLine()) != null) {
                System.out.println(str);
                arrayList.add(str);
            }
            heartDataService.saveHeartData(arrayList,57L);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @PostMapping("/getListRateForUser")
    @ResponseBody
    @PassToken
    public AjaxResult getListRateForUser(@RequestBody SingleLongArray array){
        try {
            Long[] ids = array.getArray();

            List<Long> longs = Arrays.asList(ids);
            System.out.println("ids="+longs);
            AjaxResult result = heartDataService.getListRateForUser(ids);
            return result;
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("查询失败").setCode(201);
        }
    }

}
